'use strict';

const Controller = require('egg').Controller;

class ReceivingAddressController extends Controller {
  async add() {
    const {
      ctx,
    } = this;
    const addressInfo = ctx.request.body;
    if (addressInfo.default_address) {
      const upCode = await ctx.service.receivingaddress.upAll_defaultAddress(addressInfo.userid);
      if (upCode.status === 200 || upCode.upres[0] < 20) {
        const result = await ctx.service.receivingaddress.add(addressInfo);
        ctx.body = result;
      } else {
        ctx.body = {
          status: 400,
          data: {
            msg: '请刷新后重试或收货地址已超过20个',
          },
        };
      }
      return;
    }
    const result = await ctx.service.receivingaddress.add(addressInfo);
    ctx.body = result;
  }
  async getAddress() {
    const {
      ctx,
    } = this;
    const userid = ctx.params.userid;
    const address = await ctx.service.receivingaddress.selAll(userid);
    if (address) {
      ctx.body = {
        status: 200,
        data: {
          msg: '获取数据成功',
          address,
        },
      };
      return;
    }
    ctx.body = {
      status: 400,
      data: {
        msg: '获取地址失败请刷新',
      },
    };
  }
  async upAddress() {
    const { ctx } = this;
    const upAddressInfo = ctx.request.body;
    const result = await ctx.service.receivingaddress.upAddress(upAddressInfo);
    ctx.body = result;
  }
  async delAddress() {
    const { ctx } = this;
    const delId = ctx.params.id;
    const result = ctx.model.Receivingaddress.destroy({
      where: {
        id: delId,
      },
    });
    if (result) {
      ctx.body = {
        status: 200,
        data: {
          msg: '删除收货地址成功',
        },
      };
      return;
    }
    ctx.body = {
      status: 400,
      data: {
        msg: '删除收货地址失败，请重试',
      },
    };
  }
  async setdefault() {
    const { ctx } = this;
    const upInfo = ctx.request.body;
    const result = await ctx.service.receivingaddress.upAll_defaultAddress(upInfo.userid);
    if (result.status === 200) {
      const res = await ctx.model.Receivingaddress.update(
        {
          default_address: true,
        },
        {
          where: {
            id: upInfo.id,
          },
        }
      );
      if (res) {
        ctx.body = {
          status: 200,
          data: {
            msg: '设置成功',
          },
        };
        return;
      }
      ctx.body = {
        status: 400,
        data: {
          msg: '设置失败,请重试',
        },
      };
    }
  }
}

module.exports = ReceivingAddressController;
